<template>
  <div class="cache-manager">
    <el-card class="box-card">
      <!-- 缓存统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-title">命中率</div>
            <div class="stats-value">{{ cacheStats.hitRate * 100 }}%</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-title">命中次数</div>
            <div class="stats-value">{{ cacheStats.hitCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-title">未命中次数</div>
            <div class="stats-value">{{ cacheStats.missCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-title">缓存淘汰次数</div>
            <div class="stats-value">{{ cacheStats.evictionCount }}</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <div class="operation-bar">
        <el-button type="primary" @click="refreshCache">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
        <el-button type="danger" @click="clearCache">
          <i class="el-icon-delete"></i> 清空缓存
        </el-button>
      </div>

      <!-- 缓存详情表格 -->
      <el-table
        :data="cacheList"
        style="width: 100%"
        border>
        <el-table-column
          prop="key"
          label="缓存Key"
          width="180">
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          width="120">
        </el-table-column>
        <el-table-column
          prop="size"
          label="大小"
          width="100">
        </el-table-column>
        <el-table-column
          label="菜单类型统计"
          width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.menuTypeCount">
              <div v-for="(count, type) in scope.row.menuTypeCount" :key="type">
                {{ getMenuTypeName(type) }}: {{ count }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="viewCacheDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 缓存详情对话框 -->
    <el-dialog
      title="缓存详情"
      :visible.sync="dialogVisible"
      width="50%">
      <pre class="cache-detail">{{ JSON.stringify(currentCacheDetail, null, 2) }}</pre>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CacheManager',
  data() {
    return {
      cacheStats: {
        hitCount: 0,
        missCount: 0,
        hitRate: 0,
        missRate: 0,
        evictionCount: 0,
        loadFailureCount: 0,
        totalLoadTime: 0,
        averageLoadPenalty: 0,
        evictionWeight: 0,
        loadSuccessCount: 0
      },
      cacheList: [],
      dialogVisible: false,
      currentCacheDetail: null
    }
  },
  created() {
    this.loadCacheData()
  },
  methods: {
    // 加载缓存数据
    async loadCacheData() {
      try {
        // 获取缓存统计信息
        const statsResponse = await request.get('/cache/stats')
        this.cacheStats = statsResponse

        // 获取缓存详情信息
        const detailResponse = await request.get('/cache/menu-tree/detail')
        this.processCacheDetail(detailResponse)
      } catch (error) {
        console.error('加载缓存数据失败:', error)
        this.$message.error('加载缓存数据失败')
      }
    },

    // 处理缓存详情数据
    processCacheDetail(data) {
      this.cacheList = []
      // 处理除statistics之外的所有缓存数据
      Object.entries(data).forEach(([key, value]) => {
        if (key !== 'statistics' && value) {
          this.cacheList.push({
            key,
            type: value.type || 'Unknown',
            size: value.size || 0,
            menuTypeCount: value.menuTypeCount || {},
            menuTree: value.menuTree || []
          })
        }
      })
    },

    // 获取菜单类型名称
    getMenuTypeName(type) {
      const types = {
        '1': '目录',
        '2': '菜单',
        '3': '按钮'
      }
      return types[type] || '未知类型'
    },

    // 查看缓存详情
    viewCacheDetail(row) {
      this.currentCacheDetail = row.menuTree
      this.dialogVisible = true
    },

    // 刷新缓存
    async refreshCache() {
      await this.loadCacheData()
      this.$message.success('刷新成功')
    },

    // 清空缓存
    async clearCache() {
      try {
        await this.$confirm('确定要清空所有缓存吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await request.get('/cache/clear')
        this.$message.success('缓存已清空')
        await this.loadCacheData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('清空缓存失败:', error)
          this.$message.error('清空缓存失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.cache-manager {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
  padding: 20px;
}

.stats-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.operation-bar {
  margin-bottom: 20px;
}

.cache-detail {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  max-height: 500px;
  overflow-y: auto;
}

.box-card {
  margin-bottom: 20px;
}
</style> 